package cn.ljy.mes.web.controller.frontend.mobile;

import cn.ljy.common.exception.model.MyServiceException;
import cn.ljy.common.model.result.ResponseData;
import cn.ljy.mes.utils.img.ImageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

@Api(tags = "证书")
@RestController
@RequestMapping(value = "/mobile/certificate")
@Validated
public class CertificateController {
    @Autowired
    private ImageUtil imageUtil;
    //允许接口访问的最大数量，用于保证该接口的并发量。
    private final AtomicInteger accessCount = new AtomicInteger(0);
    // 允许生成证书的开始时间：2025年5月29日下午6点
    private final LocalDateTime CERTIFICATE_START_TIME = LocalDateTime.of(2025, 5, 22, 18, 0,0,0);
    //姓名集合
    private Set<String> names=new HashSet<String>(){{
        add("张三");
        add("李四");
    }};

    //二维码生成网站：https://cli.im/text/other
    @ApiOperation(value = "生成证书")
    @GetMapping("/getCertificateOfMalasong")
    public ResponseData getCertificateOfMalasong(@Length(min = 2, max = 4, message = "姓名长度必须在 {min} - {max} 之间")String name) throws Exception{
        ResponseData responseData=null;
        //1.判断时间// 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 比较当前时间是否在指定时间之后
        if(now.isAfter(CERTIFICATE_START_TIME)){
            //1.根据名字长度设置x轴坐标
            int x=165;//默认三个名字长度的位置
            if(name.length()==2){
                x=175;
            }else if(name.length()==4){
                x=155;
            }
            //2.生成证书图片
            //让并发量+1
            increaseAccessCount();
            String img64=imageUtil.writeImage("/zhengshu.png",x,485,name,22);
            //让并发量-1
            decreaseAccessCount();
            responseData=ResponseData.success(img64);
        }else{
            responseData=ResponseData.error("证书生成失败：2025年5月29日6点后才能生成证书");
        }
        return responseData;

    }

    // 增加访问计数，如果超过最大值则返回 false
    private void increaseAccessCount() {
        int current = accessCount.get();
        if (current >= 5) {
            throw new MyServiceException("系统当前访问人数过多，请稍后访问");
        }
        accessCount.compareAndSet(current, current + 1);
    }

    // 减少访问计数
    private void decreaseAccessCount() {
        accessCount.decrementAndGet();
    }
}
